package com.ddstation.common.exception;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.ddstation.common.property.GlobalExceptionAlarmProperties;
import com.ddstation.common.wx_msg.service.WxMessageServiceItf;

public class GlobalExceptionResolver implements HandlerExceptionResolver {

    @Override
	public ModelAndView resolveException(
                        HttpServletRequest request,
                        HttpServletResponse response,
                        Object object,
                        Exception ex) {

    	logger.error("exception:", ex);
    	
    	// 警报通知
    	if(GlobalExceptionAlarmProperties.ALARM_ON) {
    		String title = "卫监平台警报";
    		if(StringUtils.isNotBlank(GlobalExceptionAlarmProperties.SERVER_NAME)) {
				title += "(" + GlobalExceptionAlarmProperties.SERVER_NAME + ")";
			}
    		
    		PrintWriter pw = null;
	    	try {
	            StringWriter sw = new StringWriter();
	            pw = new PrintWriter(sw);
	            ex.printStackTrace(pw);
	            
	            String errMessage = df.format(new Date());
	            errMessage += "\r\n\r\n" + sw.toString();
	            wxMessageService.sendToStaff(GlobalExceptionAlarmProperties.getAlermTarget(), title, errMessage, null, null);
	        } catch (Exception e2) {
	        	logger.error(e2.getMessage());
	        } finally {
	        	if (pw != null) {
	        		pw.close();
	        	}
	        }
    	}

        ModelAndView mav = new ModelAndView();

        mav.setViewName("commonError");
        return mav;

    }
    
    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionResolver.class);
    private final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
    @Inject private WxMessageServiceItf wxMessageService = null;
}
